<?php

namespace App\Console\Commands;


use App\Adv;
use App\Customer;
use App\Jobs\Send;
use App\Lead;
use App\Project;
use App\ProjectUser;
use App\Toutiao;
use App\ToutiaoLead;
use App\User;
use App\UserProject;
use Carbon\Carbon;


use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class NewJinriCommand extends Command
{


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'jinri';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
    protected $client;
    protected $customerRepository;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
        parent::__construct();

    }


//头条获取数据接口

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $toutiao = Toutiao::where('is_display', 0)->get();
        foreach ($toutiao as $item) {
            $config = $item;
            $project_id = $config['project_id'];
            if ($project_id == 21) {
                $project_id = 19;
            }
            $project = Project::find($project_id);
            $host = "https://feiyu.oceanengine.com/";
            $api = "/crm/v2/openapi/pull-clues/";
            $date_s = Carbon::today()->addDays(-10)->toDateString();
            $date_e = Carbon::tomorrow()->toDateString();
            $now = time();
            $start_date = $date_s;
            $end_date = $date_e;
            $source_data = $api . '?start_time=' . $start_date . '&end_time=' . $end_date . ' ' . $now;
            $key = $config['key'];
            $tureOrFalse = true;
            $page = 1;
            while ($tureOrFalse) {
                $result = $this->client->get('https://feiyu.oceanengine.com/crm/v2/openapi/pull-clues/', [
                    'headers' => [
                        'signature' => base64_encode(hash_hmac('sha256', $source_data, $key)),
                        'timestamp' => $now,
                        'Access-Token' => $config['token'],
                    ],
                    'query' => [
                        'start_time' => $start_date,
                        'end_time' => $end_date,
                        'page' => $page,
                        'page_size' => 100,
                    ]
                ]);
                $page++;
                $app = json_decode($result->getBody()->getContents(), true);

                if (!empty($app['data'])) {

                    foreach ($app['data'] as $v) {
                        $toutiao = ToutiaoLead::whereClueId($v['clue_id'])->first();
                        if ($toutiao) {
                            continue; //进入下次循环
                        }
                        if (!$toutiao) {
                            $v['token'] = $config['token'];
                            $v['key'] = $config['key'];
                            $toutiao = ToutiaoLead::create($v);
                            $this->info($toutiao->toJson());
                        }
                        //查询lead是否有
                        $lead = Lead::whereClueId($v['clue_id'])
                            ->first();
                     //   $leads = Lead::where('project_id', '=', $project_id)->where('mobile', '=', $toutiao->telphone)->first();
               /*         if ($leads) {
                           $customer= Customer::find($leads->customer_id);
                           $customer->is_sea=0;
                           $customer->create_time=time();
                           $customer->update_time=time();
                           $customer->save();
                            if (config('app.env') === 'production') {
                                try {
                                    $user = User::find($leads->owner_user_id);
                                    if ($user) {
                                        $user->notify(new \App\Notifications\LeadsNotification($leads));
                                    }
                                } catch (\Exception $exception) {

                                }
                            }
                            \Log::info('重复线索', $leads->toArray());
                        }*/
                        if (!$lead) {
                            $lead = new Lead();
                            $lead->clue_id = $toutiao->clue_id;
                            $lead->customer_id = 0;
                            $lead->is_transform = 0;
                            $lead->name = $toutiao->name;
                            $lead->source = $toutiao->appname == '' ? '其他渠道' : $toutiao->appname;
                            $lead->detail_address = $toutiao->location . $toutiao->address;
                            $lead->remark = $toutiao->remark;
                            // $moduleName = trim(preg_replace("/\\d+/", '', str_replace('电话', '', $toutiao->module_name)));
                            $moduleName = $toutiao->module_name;
                            $realnames = User::pluck('realname');
                            $moduleUser = '';
                            foreach ($realnames as $name) {
                                if (strstr($moduleName, $name)) {
                                    $moduleUser = $name;
                                }
                            }
                            $this->info($moduleName);
                            if (isset($config['owner_user_id'])) {
                                $owner_user_id = $config['owner_user_id'];
                            } elseif ($moduleName && $moduleUser) {
                                $user = User::where('realname', $moduleUser)->first();
                                $owner_user_id = $user->id;
                                /*      if ($project->type==0){
                                          $userProject=  UserProject::whereAdminUserId($user->id)->where('project_id',$project_id)->first();
                                          $userProject->num=1;
                                          $userProject->save();
                                      }elseif ($project->type==1){
                                          $userProject=   ProjectUser::whereUserId($user->id)->where('project_id',$project_id)->first();
                                          $userProject->num=1;
                                          $userProject->save();
                                      }*/

                            } elseif ($project->type == 0) {
                                $userProject = new  UserProject();
                                $owner_user_id = $userProject->current($project_id);
                            } elseif ($project->type == 1) {
                                $userProject = new ProjectUser();
                                $owner_user_id = $userProject->current($project_id);
                            } else {
                                $owner_user_id = 1;
                            }
                            //查询adv_id
                            $adv = Adv::whereAdvId($toutiao->adv_id)->first();
                            if ($adv) {
                                $create_user_id = $adv->user_id;
                            } else {
                                $create_user_id = 1;
                            }
                            //   project_id=24&create_user_id=9
                            if ($project_id == 24 && $create_user_id == 9) {
                                $create_user_id = 7;
                            }
                            if ($project_id == 23 || $project_id == 19) {
                                $create_user_id = 66;
                            }
                            if ($create_user_id == 66) {
                                $create_user_id = 7;
                            }
                            if ($project_id == 33 || $project_id == 30) {
                                $create_user_id = 96;
                            }
                            if ($project_id == 16) {
                                $create_user_id = 7;
                            }

                            //碧桂园林佳明
                            if ($project_id == 29 && $create_user_id = 86) {
                                $create_user_id = 111;
                            }
                            //高宏设置成刘康
                            if ($project_id== 35 ||$project_id== 48 ){
                                $create_user_id=161;
                            }
                            $lead->create_user_id = $create_user_id;
                            $lead->mobile = $toutiao->telphone;
                            $lead->owner_user_id = $owner_user_id;
                            $lead->next_time = 0;
                            if (isset($v['remark_dict']['需求面积'])) {
                                $lead->crm_vfnlcv = $v['remark_dict']['需求面积'];
                            }
                            if (isset($v['remark_dict']['您的行业'])) {
                                $lead->industry = $v['remark_dict']['您的行业'];
                            }
                            $lead->create_time = $toutiao->create_time;
                            $lead->status = '潜在客户';
                            $lead->project_id = $project_id;
                            $lead->update_time = $toutiao->create_time;
                            $lead->save();
                            if (config('app.env') === 'production') {
                                try {
                                    if ($owner_user_id == 1) {
                                        dispatch(new Send($lead));
                                    } else {
                                        $user = User::find($owner_user_id);
                                        if ($user) {
                                            $user->notify(new \App\Notifications\LeadsNotification($lead));
                                        }
                                    }
                                } catch (\Exception $exception) {

                                }
                            }
                            \Log::info('新增线索', $lead->toArray());
                        }
                    }

                } else {
                    $tureOrFalse = false;
                }
            }
        }
    }
}
